package com.zdft.promotion.common.util;

import com.zdft.promotion.common.model.UploadResultModel;
import com.zdft.promotion.sso.vo.UserBaseVO;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class FileUtil {

    public static UploadResultModel importFile(String pathPrix, MultipartFile file, UserBaseVO userBaseVO) throws IOException {
        String extName = getExt(file.getOriginalFilename());
        String fileName = UUID.randomUUID().toString();
        //完整地址名称
        String filePath = getFileName(pathPrix, fileName + extName);
        //文件存储到本地
        file.transferTo(new File(filePath));
        UploadResultModel model = new UploadResultModel(fileName);
        model.setFilePath(filePath);
        return model;
    }

    /**
     * 获取文件扩展名
     *
     * @return
     */
    public static String getExt(String filename) {
        int index = filename.lastIndexOf(".");
        if (index == -1) {
            return null;
        }
        String result = filename.substring(index);
        return result;
    }

    /**
     * 获取最终文件名
     *
     * @param pathPrix
     * @param pathPrix 存储路径前缀
     * @return
     */
    public static String getFileName(String pathPrix, String fullName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String pathDir = sdf.format(new Date());
        String filePath = pathPrix + File.separator + pathDir + File.separator;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return filePath + fullName;
    }

    public static String getPartFileName(String pathPrix, String fullName) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String pathDir = sdf.format(new Date());
        String partPath = pathDir + File.separator;
        String filePath = pathPrix + File.separator + partPath;
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return partPath + File.separator + fullName;
    }
}
